<template>
  <div class="residency-application">
    <h1>桂林电子科技大学科技园众创空间</h1>
    <h2>入驻申请书(学生)</h2>
    <div v-if="form.status !== undefined" class="status-display">
      <el-tag :type="getStatusType(form.status)" size="large" effect="dark">
        {{ getStatusText(form.status) }}
      </el-tag>
    </div>
    <el-form :model="form" :rules="formRules" label-width="150px" ref="ruleFormRef" style="max-width: 1200px; width: 100%" :disabled="form.status !== undefined && form.status !== 0">
      <!-- 基本信息 -->
      <el-card>
        <div slot="header" class="header">基本信息</div>
        <el-form-item label="团队/公司名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入团队或公司的名称" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="申请日期" prop="applyDate">
              <el-date-picker v-model="form.applyDate" type="date" placeholder="点击选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团队/公司人数" prop="numbers">
              <el-input-number v-model="form.numbers" :min="1" placeholder="请输入团队人数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入项目的名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="所属行业" prop="industry">
          <el-radio-group v-model="form.industry">
            <el-radio label="电子信息产业" value="电子信息产业">电子信息产业</el-radio>
            <el-radio label="生物医学产业" value="生物医学产业">生物医学产业</el-radio>
            <el-radio label="新能源产业" value="新能源产业">新能源产业</el-radio>
            <el-radio label="新材料产业" value="新材料产业">新材料产业</el-radio>
            <el-radio label="先进制造产业" value="先进制造产业">先进制造产业</el-radio>
            <el-radio label="环保节能减排" value="环保节能减排">环保节能减排</el-radio>
            <el-radio label="高技术服务业" value="高技术服务业">高技术服务业</el-radio>
            <el-radio label="软件外包服务业" value="软件外包服务业">软件外包服务业</el-radio>
            <el-radio label="其他" :value="otherIndustry">
              其他
              <el-input
                  v-model="otherIndustry"
                  placeholder="请填写其他行业"
                  style="margin-left: 10px; width: 200px"
              />
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>

      <!-- 联系人信息 -->
      <el-card>
        <div slot="header" class="header">联系人信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人的姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系人的电话号码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 公司信息 -->
      <el-card>
        <div slot="header" class="header">公司信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="公司注册时间" prop="registerDate">
              <el-date-picker v-model="form.registerDate" type="date" placeholder="点击选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司组织机构代码" prop="organizationCode">
              <el-input v-model="form.organizationCode" placeholder="请输入公司组织机构代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="公司注册资金" prop="registerMoney">
          <el-input-number
              v-model="form.registerMoney"
              :min="0"
              :max="1000000000"
              placeholder="请输入公司注册资金"
          />
          <span>元</span>
        </el-form-item>
        <el-form-item label="项目/公司股权构成(%)" prop="shareholdingRatio">
          <el-input
              v-model="form.shareholdingRatio"
              type="textarea"
              placeholder="请详细描述项目或公司的股权分配情况"
          />
        </el-form-item>
        <el-form-item label="是否经指导老师审批" prop="teacherApproved">
          <el-radio-group v-model="form.teacherApproved">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否经学院审批" prop="collegeApproved">
          <el-radio-group v-model="form.collegeApproved">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否有实际入驻场地" prop="hasPhysicalSpace">
          <el-radio-group v-model="form.hasPhysicalSpace" @change="handleSpaceChange">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="卡座号" prop="seatNumber" v-if="form.hasPhysicalSpace">
          <el-input v-model="form.seatNumber" placeholder="请输入卡座号" />
        </el-form-item>
        <el-form-item label="经营范围（产品/服务）" prop="businessScope">
          <el-input
              v-model="form.businessScope"
              type="textarea"
              placeholder="请简要说明公司的主要产品或服务"
          />
        </el-form-item>
      </el-card>

      <!-- 缴费信息 -->
      <el-card>
        <div slot="header" class="header">缴费信息</div>
        <el-form-item label="缴费类型" prop="paymentTypes">
          <el-checkbox-group v-model="form.paymentTypes">
            <el-checkbox label="保证金">保证金</el-checkbox>
            <el-checkbox label="卡座使用费">卡座使用费</el-checkbox>
            <el-checkbox label="管理费">管理费</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="缴费金额" prop="paymentAmount">
          <el-input-number
              v-model="form.paymentAmount"
              :min="0"
              :precision="2"
              placeholder="请输入缴费金额"
          />
          <span>元</span>
        </el-form-item>
      </el-card>

      <!-- 指导老师信息 -->
      <el-card>
        <div slot="header" class="header">指导老师信息</div>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="指导老师姓名" prop="teacherName">
              <el-input v-model="form.teacherName" placeholder="请输入指导老师姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="指导老师联系方式" prop="teacherPhone">
              <el-input v-model="form.teacherPhone" placeholder="请输入指导老师电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="指导老师所在学院" prop="teacherDepartment">
              <el-input v-model="form.teacherDepartment" placeholder="请输入指导老师所在学院" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="指导老师职务" prop="teacherJob">
          <el-input v-model="form.teacherJob" placeholder="请输入指导老师职务" />
        </el-form-item>
      </el-card>

      <!-- 主要成员信息 -->
      <el-card>
        <div slot="header" class="header">主要成员信息</div>
        <el-form-item label-width="0" prop="members">
          <el-button type="primary" @click="addMember">增加成员</el-button>
          <el-table :data="form.members" style="width: 100%">
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column prop="name" label="姓名">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.name'"
                  :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
                  <el-input v-model="scope.row.name" placeholder="请输入成员姓名" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="department" label="学院/部门">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.department'"
                  :rules="[{ required: true, message: '请输入所属学院或部门', trigger: 'blur' }]">
                  <el-input v-model="scope.row.department" placeholder="请输入所属学院或部门" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="major" label="本科/研究生/应届毕业生">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.major'"
                  :rules="[{ required: true, message: '请输入身份', trigger: 'blur' }]">
                  <el-input v-model="scope.row.major" placeholder="请输入本科/研究生/应届毕业生" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号码">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.phone'"
                  :rules="[{ required: true, message: '请输入手机号码', trigger: 'blur' },{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }]">
                  <el-input v-model="scope.row.phone" placeholder="请输入手机号码" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="qq" label="QQ号">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.qq'"
                  :rules="[{ required: true, message: '请输入QQ号码', trigger: 'blur' },{ pattern: /^[1-9][0-9]{4,11}$/, message: '请输入正确的QQ号码', trigger: 'blur' }]">
                  <el-input v-model="scope.row.qq" placeholder="请输入QQ号码" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="job" label="公司/团队职务">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.job'"
                  :rules="[{ required: true, message: '请输入在公司或团队中的职务', trigger: 'blur' }]">
                  <el-input v-model="scope.row.job" placeholder="请输入在公司或团队中的职务" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="removeMember(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-card>

      <!-- 项目信息 -->
      <el-card>
        <div slot="header" class="header">项目信息</div>
        <el-form-item label="项目/公司简介（300字以内）" prop="projectIntroduction">
          <el-input
              v-model="form.projectIntroduction"
              type="textarea"
              placeholder="请用300字以内的文字介绍您的项目或公司"
          />
        </el-form-item>
        <el-form-item
            label="您想获得的帮助（如创业辅导、投融资服务、市场推广）"
            prop="helpDescription"
        >
          <el-input
              v-model="form.helpDescription"
              type="textarea"
              placeholder="请告诉我们您希望得到哪些帮助"
          />
        </el-form-item>
      </el-card>

      <!-- 文件上传 -->
      <el-card>
        <div slot="header" class="header">文件上传</div>
        <el-form-item label="身份证明材料" prop="certificate">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'certificate')"
              :on-preview="handleFilePreview"
              :on-remove="(file) => handleFileRemove(file, 'certificate')"
              :limit="1"
              :file-list="certificateList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传身份证、学生证复印件，支持jpg/png/pdf格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目相关文件" prop="projectfile">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'projectfile')"
              :on-preview="handleFilePreview"
              :on-remove="(file) => handleFileRemove(file, 'projectfile')"
              :limit="5"
              :file-list="projectFileList"
              multiple
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传项目相关文件（如奖项、专利、图片等），支持jpg/png/pdf格式，最多5个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="缴费回单" prop="paymentReceipt">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'paymentReceipt')"
              :on-preview="handleFilePreview"
              :on-remove="(file) => handleFileRemove(file, 'paymentReceipt')"
              :limit="1"
              :file-list="paymentReceiptList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传缴费回单，支持jpg/png/pdf格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-card>

      <!-- 承诺 -->
      <el-card>
        <div slot="header" class="header">承诺</div>
        <el-form-item class="promise-text">
          <p>
            本团队(公司)承诺上述内容属实，如有任何虚假与隐瞒,本团队(公司)愿承担一切法律责任和后果。
          </p>
          <p>承诺人: <el-input v-model="form.contactName" placeholder="请在此签名"></el-input></p>
          <p>
            日期: <el-date-picker v-model="form.applyDate" type="date" placeholder="请选择签署日期" />
          </p>
        </el-form-item>
      </el-card>

      <!-- 审批意见 -->
      <el-card>
        <div slot="header" class="header">审批意见</div>
        <el-form-item label="办公室主任意见">
          <el-input disabled type="textarea" placeholder="等待办公室主任填写意见" />
        </el-form-item>
        <el-form-item label="领导审批意见">
          <el-input disabled type="textarea" placeholder="等待领导填写审批意见" />
        </el-form-item>
      </el-card>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button v-if="form.status === 0" type="primary" @click="submitForm">提交</el-button>
        <el-button v-if="form.status === 0" @click="saveDraft">保存草稿</el-button>
        <el-button v-if="form.status === 0" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <span>注：请同时提供团队成员身份证、学生证/教师证复印件及项目相关文件（如奖项、专利、图片等）。</span>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, watch, onMounted } from 'vue';
  import { ElMessage,type UploadFile, } from 'element-plus';
  import {
    zcresidencyApplication,
    getApplicationFromId,
    editApplication,
    residencyApplicationList,
  } from '@/api/enterpeise';
  import type {ResidencyApplication, ResidencyApplicationStudent} from '@/types/type';
  import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
  import FileUpload from '../../components/fileUpload.vue';
  import { getLoginUserId } from '@/utils/storage';
  import { uploadFile } from '@/api/file';
  import { useRoute } from 'vue-router';
  import router from "@/router";

  const route = useRoute();
  const ruleFormRef = ref<FormInstance>();
  const isSubmit = ref(false);
  //其他行业
  const otherIndustry = ref('');
  const totalRecord = ref(0); // 标记是否为编辑

  // 类型合并，保证所有字段都在
  type StudentMember = {
    name: string;
    department: string;
    major: string;
    phone: string;
    qq: string;
    job: string;
  };
  type StudentFormType = {
    status?: number;
    id?: number;
    userId?: number;
    type: number;
    name: string;
    applyDate: string;
    itemName: string;
    numbers: number;
    contactName: string;
    contactPhone: string;
    industry: string;
    registerDate: string;
    organizationCode: string;
    registerMoney: number;
    shareholdingRatio: string;
    teacherApproved: boolean;
    collegeApproved: boolean;
    hasPhysicalSpace: boolean;
    seatNumber: string;
    businessScope: string;
    teacherName: string;
    teacherPhone: string;
    teacherDepartment: string;
    teacherJob: string;
    paymentType: string;
    paymentTypes: string[]; // 用于前端多选框绑定
    paymentAmount: number;
    members: StudentMember[];
    projectIntroduction: string;
    helpDescription: string;
    teacherOpinion: string;
    collegeOpinion: string;
    officeOpinion: string;
    leaderOpinion: string;
    certificate?: any;
    projectfile?: any;
    paymentReceipt?: any;
    // 添加后端实体类中存在的字段
    isQualified?: boolean;
    isCollege?: boolean;
    schoolLeavingCertificate?: string;
  };

  const form = reactive<StudentFormType>({
    status: 0,
    id: undefined,
    userId: undefined,
    type: 0,
    name: '',
    applyDate: '',
    itemName: '',
    numbers: 0,
    contactName: '',
    contactPhone: '',
    industry: '',
    registerDate: '',
    organizationCode: '',
    registerMoney: 0.0,
    shareholdingRatio: '',
    teacherApproved: false,
    collegeApproved: false,
    hasPhysicalSpace: false,
    seatNumber: '',
    businessScope: '',
    teacherName: '',
    teacherPhone: '',
    teacherDepartment: '',
    teacherJob: '',
    paymentType: '',
    paymentTypes: [], // 用于前端多选框绑定
    paymentAmount: 0,
    members: [
      {
        name: '',
        department: '',
        major: '',
        phone: '',
        qq: '',
        job: '',
      },
    ],
    projectIntroduction: '',
    helpDescription: '',
    teacherOpinion: '',
    collegeOpinion: '',
    officeOpinion: '',
    leaderOpinion: '',
    certificate: undefined,
    projectfile: undefined,
    paymentReceipt: undefined,
    // 添加后端实体类中存在的字段
    isQualified: undefined,
    isCollege: undefined,
    schoolLeavingCertificate: undefined,
  });

  // 处理是否有实际入驻场地变化
  const handleSpaceChange = (val: string | number | boolean | undefined) => {
    if (!val) {
      form.seatNumber = '';
    }
  };

  // 获取模式（查看/编辑）
  const mode = ref(route.query.mode as string || 'view');

  // 获取详情
  const getDetail = async (id: number) => {
    try {
      const res = await getApplicationFromId(id) as any;
      if (res.code === 200) {
        // 字段映射
        const data = res.data;
        // 处理行业字段
        const industryValue = data.industry || data.industryType || '';
        const predefinedIndustries = [
          '电子信息产业', '生物医学产业', '新能源产业', '新材料产业',
          '先进制造产业', '环保节能减排', '高技术服务业', '软件外包服务业'
        ];

        if (predefinedIndustries.includes(industryValue)) {
          // 如果是预定义行业，直接设置
          form.industry = industryValue;
          otherIndustry.value = '';
        } else if (industryValue) {
          // 如果是自定义行业，设置为其他选项
          form.industry = industryValue;
          otherIndustry.value = industryValue;
        } else {
          form.industry = '';
          otherIndustry.value = '';
        }
        form.registerDate = data.registerDate || data.register_date || '';
        form.organizationCode = data.organizationCode || data.organization_code || '';
        
        // 处理缴费类型字段，将逗号分隔的字符串转换为数组
        if (data.paymentType) {
          form.paymentTypes = data.paymentType.split(',').map((item: string) => item.trim());
        } else {
          form.paymentTypes = [];
        }
        
        form.paymentAmount = data.paymentAmount || data.payment_amount || 0;

        // 处理指导老师信息 - 从teachers数组中提取第一个老师的信息
        if (data.teachers && data.teachers.length > 0) {
          const teacher = data.teachers[0];
          form.teacherName = teacher.name || '';
          form.teacherPhone = teacher.phone || '';
          form.teacherDepartment = teacher.department || '';
          form.teacherJob = teacher.job || '';
        } else {
          // 兼容旧的字段名
          form.teacherName = data.teacherName || data.teacher_name || '';
          form.teacherPhone = data.teacherPhone || data.teacher_phone || '';
          form.teacherDepartment = data.teacherDepartment || data.teacher_department || '';
          form.teacherJob = data.teacherJob || data.teacher_job || '';
        }

        // 处理其他字段映射
        form.teacherApproved = data.isTeacherApproval !== undefined ? data.isTeacherApproval : data.teacherApproved;
        form.collegeApproved = data.isQualified !== undefined ? data.isQualified : data.collegeApproved;
        form.hasPhysicalSpace = data.isRealIn !== undefined ? data.isRealIn : data.hasPhysicalSpace;
        form.paymentReceipt = data.paymentCertificate || data.paymentReceipt;

        // 处理股权构成字段映射
        form.shareholdingRatio = data.shareholdingRatio || data.shareholdingRatio || '';

        // 处理文件回显
        if (data.certificate) {
          certificateList.value = [{
            name: '身份证明材料',
            url: data.certificate,
            uid: Date.now()
          }];
        }

        if (data.projectfile) {
          projectFileList.value = [{
            name: '项目相关文件',
            url: data.projectfile,
            uid: Date.now()
          }];
        }

        if (data.paymentCertificate) {
          paymentReceiptList.value = [{
            name: '缴费回单',
            url: data.paymentCertificate,
            uid: Date.now()
          }];
        }

        // 其它字段自动合并
        Object.assign(form, data);
        totalRecord.value = 1; // 编辑模式
      }
    } catch (error) {
      ElMessage.error('获取详情失败');
    }
  };

  // 监听表单数据变化并保存到 localStorage
  watch(
      form,
      (newForm) => {
        localStorage.setItem('ResidencyApplicationStudentForm', JSON.stringify(newForm));
      },
      { deep: true }
  );

  // 监听其他行业输入变化
  watch(
      otherIndustry,
      (newValue) => {
        if (form.industry === newValue || (form.industry === '' && newValue)) {
          form.industry = newValue;
        }
      }
  );

  // 监听行业选择变化
  watch(
      () => form.industry,
      (newValue) => {
        // 如果选择的不是其他行业，清空otherIndustry
        const predefinedIndustries = [
          '电子信息产业', '生物医学产业', '新能源产业', '新材料产业',
          '先进制造产业', '环保节能减排', '高技术服务业', '软件外包服务业'
        ];
        if (predefinedIndustries.includes(newValue)) {
          otherIndustry.value = '';
        }
      }
  );

  // 增加成员
  const addMember = () => {
    ruleFormRef.value?.clearValidate('members')
    form.members.push({
      name: '',
      department: '',
      major: '',
      phone: '',
      qq: '',
      job: '',
    });
  };

  // 删除成员
  const removeMember = (index: number) => {
    form.members.splice(index, 1);
  };

  const formRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入团队/公司名称', trigger: 'blur' }],
    applyDate: [{ type: 'date', required: true, message: '请选择申请日期', trigger: 'change' }],
    numbers: [{ type: 'number', required: true, message: '请输入团队人数', trigger: 'blur' }],
    itemName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
    contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
    contactPhone: [
      { required: true, message: '请输入联系方式', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    registerDate: [{ type: 'date', required: true, message: '请选择公司注册时间', trigger: 'change' }],
    organizationCode: [{ required: true, message: '请输入公司组织机构代码', trigger: 'blur' }],
    registerMoney: [
      { type: 'number', required: true, message: '请输入公司注册资金', trigger: 'blur' },
    ],
    ShareholdingRatio: [
      { required: true, message: '请输入项目/公司股权构成', trigger: 'blur' },
      { pattern: /^[\d%.,，]*\d+(\.\d+)?[\d%.,，]*$/, message: '只能包含数字、百分号、小数点和逗号，如：张三40%，李四60%', trigger: 'blur' }
    ],
    teacherApproved: [{ required: true, message: '请选择是否经指导老师审批', trigger: 'change' }],
    collegeApproved: [{ required: true, message: '请选择是否经学院审批', trigger: 'change' }],
    hasPhysicalSpace: [{ required: true, message: '请选择是否有实际入驻场地', trigger: 'change' }],
    seatNumber: [{ required: true, message: '请输入卡座号', trigger: 'blur' }],
    businessScope: [{ required: true, message: '请输入经营范围', trigger: 'blur' }],
    paymentTypes: [{ type: 'array', required: true, message: '请选择缴费类型', trigger: 'change' }],
    paymentAmount: [{ type: 'number', required: true, message: '请输入缴费金额', trigger: 'blur' }],
    teacherName: [{ required: true, message: '请输入指导老师姓名', trigger: 'blur' }],
    teacherPhone: [
      { required: true, message: '请输入指导老师联系方式', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    teacherDepartment: [{ required: true, message: '请输入指导老师所在学院', trigger: 'blur' }],
    teacherJob: [{ required: true, message: '请输入指导老师职务', trigger: 'blur' }],
    projectIntroduction: [{ required: true, message: '请输入项目/公司简介', trigger: 'blur' }],
    helpDescription: [{ required: true, message: '请输入您想获得的帮助', trigger: 'blur' }],
    members: [{
      type: 'array',
      required: true,
      message: '请至少添加一个主要人员信息',
      trigger: 'change'
    }],
    'members.name': [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    'members.department': [{ required: true, message: '请输入学院/部门', trigger: 'blur' }],
    'members.major': [{ required: true, message: '请输入专业方向', trigger: 'blur' }],
    'members.phone': [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    'members.qq': [{ required: true, message: '请输入QQ号', trigger: 'blur' }],
    'members.job': [{ required: true, message: '请输入公司/团队职务', trigger: 'blur' }],
  });

  // 添加文件列表的响应式变量
  const certificateList = ref<UploadFile[]>([]);
  const projectFileList = ref<UploadFile[]>([]);
  const paymentReceiptList = ref<UploadFile[]>([]); // 新增缴费回单文件列表

  // 通用文件上传方法
  const handleFileUpload = async (file: UploadFile, field: 'certificate' | 'paymentReceipt' | 'projectfile') => {
    if (!file.raw) return;
    const isValidFormat = file.raw.type.includes('image/') || file.raw.type === 'application/pdf';
    if (!isValidFormat) {
      ElMessage.error('只能上传jpg/png/pdf格式的文件！');
      return false;
    }
    const formData = new FormData();
    formData.append('file', file.raw);
    try {
      const res = await uploadFile(formData);
      ElMessage.success('上传成功');

      if (field === 'projectfile') {
        // 项目文件支持多个，用逗号分隔
        const currentUrls = form.projectfile ? form.projectfile.split(',') : [];
        currentUrls.push(res.data.url);
        form.projectfile = currentUrls.join(',');

        // 更新文件列表
        projectFileList.value.push({...file, url: res.data.url, uid: Date.now()});
      } else {
        // 单个文件字段
        (form as any)[field] = res.data.url;

        // 设置file-list
        if (field === 'certificate') {
          certificateList.value = [{...file, url: res.data.url, uid: Date.now()}];
        } else if (field === 'paymentReceipt') {
          paymentReceiptList.value = [{...file, url: res.data.url, uid: Date.now()}];
        }
      }
    } catch (error) {
      ElMessage.error('上传失败');
    }
  };

  // 文件预览方法
  const handleFilePreview = (file: UploadFile) => {
    if (file.url) {
      window.open(file.url, '_blank');
    }
  };

  // 文件删除方法
  const handleFileRemove = (file: UploadFile, field: 'certificate' | 'paymentReceipt' | 'projectfile') => {
    if (field === 'projectfile') {
      // 项目文件支持多个，从逗号分隔的字符串中移除指定文件
      const currentUrls = form.projectfile ? form.projectfile.split(',') : [];
      const updatedUrls = currentUrls.filter(url => url !== file.url);
      form.projectfile = updatedUrls.join(',');

      // 更新文件列表
      projectFileList.value = projectFileList.value.filter(f => f.url !== file.url);
    } else {
      // 单个文件字段
      (form as any)[field] = '';

      // 清空对应的文件列表
      if (field === 'certificate') {
        certificateList.value = [];
      } else if (field === 'paymentReceipt') {
        paymentReceiptList.value = [];
      }
    }

    ElMessage.success('文件已删除');
  };

  // 提交表单
  const submitForm = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          form.status = 1;

          // 格式化 registerDate 为 YYYY-MM-DD
          if (form.registerDate) {
            if (typeof form.registerDate === 'string') {
              const date = new Date(form.registerDate);
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0');
              const day = String(date.getDate()).padStart(2, '0');
              form.registerDate = `${year}-${month}-${day}`;
            } else if (form.registerDate instanceof Date) {
              const year = form.registerDate.getFullYear();
              const month = String(form.registerDate.getMonth() + 1).padStart(2, '0');
              const day = String(form.registerDate.getDate()).padStart(2, '0');
              form.registerDate = `${year}-${month}-${day}`;
            }
          }

          // 格式化 applyDate 为 YYYY-MM-DD
          if (form.applyDate) {
            if (typeof form.applyDate === 'string') {
              const date = new Date(form.applyDate);
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0');
              const day = String(date.getDate()).padStart(2, '0');
              form.applyDate = `${year}-${month}-${day}`;
            } else if (form.applyDate instanceof Date) {
              const year = form.applyDate.getFullYear();
              const month = String(form.applyDate.getMonth() + 1).padStart(2, '0');
              const day = String(form.applyDate.getDate()).padStart(2, '0');
              form.applyDate = `${year}-${month}-${day}`;
            }
          }

          // 处理 projectfile 字段
          const projectfileBak = form.projectfile;
          if (Array.isArray(form.projectfile)) {
            form.projectfile = form.projectfile.length > 0 ? form.projectfile.join(',') : '';
          }

          // 处理 undefined 字段为 ''
          ['certificate', 'projectfile', 'paymentReceipt', 'id', 'seatNumber'].forEach(key => {
            if ((form as any)[key] === undefined) {
              (form as any)[key] = '';
            }
          });

          // 构建提交数据，只包含后端实体类中存在的字段
          const submitData: any = {
            name: form.name,
            registerDate: form.registerDate,
            organizationCode: form.organizationCode,
            industry: form.industry,
            applyDate: form.applyDate,
            itemName: form.itemName,
            numbers: form.numbers,
            contactName: form.contactName,
            contactPhone: form.contactPhone,
            registerMoney: form.registerMoney,
            shareholdingRatio: form.shareholdingRatio,
            isTeacherApproval: form.teacherApproved,
            isRealIn: form.hasPhysicalSpace,
            isQualified: form.collegeApproved,
            isQualified: form.collegeApproved,
            paymentType: form.paymentType,
            paymentCertificate: form.paymentReceipt || '',
            businessScope: form.businessScope,
            projectIntroduction: form.projectIntroduction,
            helpDescription: form.helpDescription,
            teacherOpinion: form.teacherOpinion || '',
            collegeOpinion: form.collegeOpinion || '',
            officeOpinion: form.officeOpinion || '',
            leaderOpinion: form.leaderOpinion || '',
            status: form.status,
            type: form.type,
            certificate: form.certificate || '',
            projectfile: form.projectfile || '',
            // 构建指导老师信息数组
            teachers: [{
              name: form.teacherName,
              phone: form.teacherPhone,
              department: form.teacherDepartment,
              job: form.teacherJob
            }],
            // 确保成员信息正确传递
            members: form.members.map(member => ({
              name: member.name,
              department: member.department,
              major: member.major,
              phone: member.phone,
              qq: member.qq,
              job: member.job
            }))
          };

          // 如果有实际入驻场地，添加卡座号
          if (form.hasPhysicalSpace && form.seatNumber) {
            submitData.seatNumber = form.seatNumber;
          }

          // 如果是编辑模式，添加id
          if (form.id) {
            submitData.id = form.id;
          }

          const api = form.id ? editApplication : zcresidencyApplication;
          const res = await api(submitData) as any;

          // 还原
          form.projectfile = projectfileBak;

          if (res.code === 200) {
            ElMessage.success(mode.value === 'edit' ? '更新成功' : '提交成功');
            localStorage.removeItem('ResidencyApplicationStudentForm');
            router.push(`/personal-center/enterprise-settlement/my-application`);
          } else {
            console.error('提交失败，后端返回：', res);
            ElMessage.error(res.msg || '保存失败');
          }
        } catch (error) {
          console.error('提交异常：', error);
          ElMessage.error('提交失败');
        }
      }
    });
  };

  // 重置表单
  const resetForm = () => {
    ruleFormRef.value?.resetFields();
    localStorage.removeItem('ResidencyApplicationStudentForm'); // 重置表单时清除本地存储
  };

  // 状态标签工具函数
  const getStatusType = (status: number) => {
    switch (status) {
      case 0: return 'info';
      case 1: return 'warning';
      case 2: return 'success';
      case 3: return 'danger';
      default: return 'info';
    }
  };
  const getStatusText = (status: number) => {
    switch (status) {
      case 0: return '草稿';
      case 1: return '已提交';
      case 2: return '审核通过';
      case 3: return '审核失败';
      default: return '未知状态';
    }
  };

  // 保存草稿
  const saveDraft = async () => {
    try {
      form.status = 0;
      // 格式化 registerDate 为 YYYY-MM-DD
      if (form.registerDate) {
        if (typeof form.registerDate === 'string') {
          const date = new Date(form.registerDate);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          form.registerDate = `${year}-${month}-${day}`;
        } else if (form.registerDate instanceof Date) {
          const year = form.registerDate.getFullYear();
          const month = String(form.registerDate.getMonth() + 1).padStart(2, '0');
          const day = String(form.registerDate.getDate()).padStart(2, '0');
          form.registerDate = `${year}-${month}-${day}`;
        }
      }

      // 格式化 applyDate 为 YYYY-MM-DD
      if (form.applyDate) {
        if (typeof form.applyDate === 'string') {
          const date = new Date(form.applyDate);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          form.applyDate = `${year}-${month}-${day}`;
        } else if (form.applyDate instanceof Date) {
          const year = form.applyDate.getFullYear();
          const month = String(form.applyDate.getMonth() + 1).padStart(2, '0');
          const day = String(form.applyDate.getDate()).padStart(2, '0');
          form.applyDate = `${year}-${month}-${day}`;
        }
      }

      // 处理 projectfile 字段
      const projectfileBak = form.projectfile;
      if (Array.isArray(form.projectfile)) {
        form.projectfile = form.projectfile.length > 0 ? form.projectfile.join(',') : '';
      }

      // 处理 undefined 字段为 ''
      ['certificate', 'projectfile', 'paymentReceipt', 'id', 'seatNumber'].forEach(key => {
        if ((form as any)[key] === undefined) {
          (form as any)[key] = '';
        }
      });

      // 构建提交数据，只包含后端实体类中存在的字段
      const submitData: any = {
        name: form.name,
        registerDate: form.registerDate,
        organizationCode: form.organizationCode,
        industry: form.industry,
        applyDate: form.applyDate,
        itemName: form.itemName,
        numbers: form.numbers,
        contactName: form.contactName,
        contactPhone: form.contactPhone,
        registerMoney: form.registerMoney,
        shareholdingRatio: form.shareholdingRatio,
        isTeacherApproval: form.teacherApproved,
        isRealIn: form.hasPhysicalSpace,
        isQualified: form.collegeApproved,
        paymentType: Array.isArray(form.paymentTypes) ? form.paymentTypes.join(',') : form.paymentType,
        paymentCertificate: form.paymentReceipt || '',
        businessScope: form.businessScope,
        projectIntroduction: form.projectIntroduction,
        helpDescription: form.helpDescription,
        teacherOpinion: form.teacherOpinion || '',
        collegeOpinion: form.collegeOpinion || '',
        officeOpinion: form.officeOpinion || '',
        leaderOpinion: form.leaderOpinion || '',
        status: form.status,
        type: form.type,
        certificate: form.certificate || '',
        projectfile: form.projectfile || '',
        // 构建指导老师信息数组
        teachers: [{
          name: form.teacherName,
          phone: form.teacherPhone,
          department: form.teacherDepartment,
          job: form.teacherJob
        }],
        // 确保成员信息正确传递
        members: form.members.map(member => ({
          name: member.name,
          department: member.department,
          major: member.major,
          phone: member.phone,
          qq: member.qq,
          job: member.job
        }))
      };

      // 如果有实际入驻场地，添加卡座号
      if (form.hasPhysicalSpace && form.seatNumber) {
        submitData.seatNumber = form.seatNumber;
      }

      // 如果是编辑模式，添加id
      if (form.id) {
        submitData.id = form.id;
      }

      const api = form.id ? editApplication : zcresidencyApplication;

      const res = await api(submitData) as any;
      // 还原
      form.projectfile = projectfileBak;

      if (res.code === 200) {
        ElMessage.success('草稿保存成功');
        localStorage.removeItem('ResidencyApplicationStudentForm');
        router.push('/personal-center/enterprise-settlement/my-application');
      } else {
        console.error('保存草稿失败，后端返回：', res);
        ElMessage.error(res.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存草稿异常：', error);
      ElMessage.error('保存失败');
    }
  };

  onMounted(() => {
    residencyApplicationList({ applicantId: getLoginUserId() }).then((res: any) => {
      if (res.code === 200) {
        isSubmit.value = res.data.total === 1;
        if (isSubmit.value) {
          ElMessage.warning('您已提交入驻申请，不能再次提交');
        }
      }
    });

    const id = route.query.id;
    if (id) {
      getDetail(Number(id));
    }
  });
</script>

<style lang="scss" scoped>
.residency-application {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  h1 {
    font-size: 24px;
    margin-bottom: 20px;
  }

  h2 {
    font-size: 20px;
    margin-bottom: 20px;
  }

  .status-display {
    margin-bottom: 20px;
  }

  .header {
    font-size: 18px;
    font-weight: bold;
  }

  .promise-text {
    p {
      margin: 10px 0;
    }
  }
}

</style>
